<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2016/11/19
 * Time: 16:22
 */

namespace SDXApi\Controller;


use SDXApi\Model\OrderActionModel;
use SDXApi\Model\OrderinfoModel;
use SDXApi\Model\PickupHandleLogModel;
use Think\Controller;

/**
 * 自提订单
 * Class PickupController
 * @package SDXApi\Controller
 */
class PickupController extends Controller
{

    /**
     * @var \Model|null|\Think\Model
     */
    protected $orderModel = null;

    /**
     * @var \Model|null|\Think\Model
     */
    protected $handleLogModel = null;

    /**
     * @var array
     */
    protected $error = array();

    /**
     * PickupController constructor.
     */
    public function __construct()
    {
        $this->orderModel = new OrderinfoModel();
        $this->handleLogModel = new PickupHandleLogModel();
    }

    /**
     * Created by Jerry
     */
    public function handle()
    {
        $this->get_pickup_order();
    }

    /**
     * 查找当天22点前下的订单，并在22：30前未确认收货的订单修改配货时间
     * Created by Jerry
     * @return bool
     */
    protected function get_pickup_order()
    {
//        判断当前执行时间
        $handle_time = date('H:i', time());
        if ($handle_time !== '22:30') {
            return false;
        }


        //设置当天22：00时间
        $time = date('Y-m-d', gmtime());
        $formatTime = strtotime($time . ' 22:00');

        $data = $this->orderModel->get_pickup_order_by_time_for_shipping_id($formatTime);

        if (empty($data)) {
            return false;
        }

//        批量修改配送时间
        $result = $this->set_pickup_order_best_time($data);

        if (!$result) {
            return false;
        }

        return true;

    }


    /**
     * 批量修改自提单配送时间
     * @author Jerry
     * @param array $orders
     * @return bool
     */
    protected function set_pickup_order_best_time($orders = array())
    {
        if (empty($orders)) {
            return false;
        }

        $time = strtotime('+1 days', gmtime());
        $best_time_start = strtotime(date('Y-m-d', $time) . ' 10:00');
        $best_time = strtotime(date('Y-m-d', $time) . ' 22:00');

        $newTimeStart = date('Y-m-d', $time) . ' 10:00';
        $newTimeEnd = date('Y-m-d', $time) . ' 22:00';

        $forend_time = strtotime(date('Y-m-d', $time) . ' 22:00');
        $smsTime['best_time'] = date('Y-m-d', $best_time_start) . ' ' . date('H:i', $best_time_start) . '-' . date('H:i', $forend_time);

        $updateData = array(
            'best_time'         =>  $best_time,
            'best_time_start'   =>  $best_time_start,
        );

        foreach ($orders as $order) {

            $rs = $this->orderModel->update_pickup_order_by_id($order['order_id'], $updateData);

//            统计是否已存在修改过日志
			$number = $this->handleLogModel->get_pickup_handle_log_by_order_id($order['order_id']);

            if (!$rs) {
                $this->insert_log('修改配送时间失败', $order['order_id']);
                continue;
            }

//            日志写入
            $oldTimeStart = date('Y-m-d H:i:s', $order['best_time_start']);
            $oldTimeEnd = date('Y-m-d H:i:s', $order['best_time']);
            $logContent = "修改配送时间成功，修改时间由：{$oldTimeStart} - {$oldTimeEnd} 改为：{$newTimeStart}-{$newTimeEnd}";
            $this->insert_log($logContent, $order['order_id']);
            $this->insert_order_action($order['order_id'], $logContent);
            
            $chat_param=array();
            switch($_SERVER['SERVER_NAME']){
                case 'api.xian3.com':
                    $thisurl='xian3.com';
                    break;
                case 'api.test.shidexian.com':
                    $thisurl='test.shidexian.com';
                    break;
                case 'api.shidexian.com':
                    $thisurl='w.shidexian.com';
                    break;
                default:
                    $thisurl='w.shidexian.com';
                    break;
            }

            $oid=$order['user_id'];
            $Code=md5($order['user_id'].'sdx@9999');
            	
            
            $chat_param['keyword1']=$order['order_sn'];
            $chat_param['keyword2']=$smsTime;
            $chat_param['keyword3']='天河区黄埔大道西120号高志大厦B1层食得鲜智能生活体验中心';
            
            if ($number > 0) {
                
                $chat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$order['order_id']."&utm_source=GZHorder_pickup_warning_new";
//            	发送短信提醒
				$smsResult = $this->send_pickup_order_sms($order['mobile'], $order['consignee'], $order['order_sn'], $order['user_id'], $smsTime, 1,$chat_param);
			}
			else
			{
			    $chat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$order['order_id']."&utm_source=GZHorder_remind_new";
//            	发送短信提醒
				$smsResult = $this->send_pickup_order_sms($order['mobile'], $order['consignee'], $order['order_sn'], $order['user_id'], $smsTime,0,$chat_param);
			}

            if(empty($smsResult)){
                $this->insert_log('发送延时配送短信失败', $order['order_id']);
            }

            $this->insert_log('发送延时配送短信成功', $order['order_id']);
        }

        return true;
    }


    /**
     * 插入操作日志
     * @author Jerry
     * @param string $log
     * @param int $order_id
     * @return mixed
     */
    protected function insert_log($log = '', $order_id = 0)
    {
        $logData = array(
            'log'           =>  $log,
            'order_id'      =>  $order_id,
            'created_at'    =>  time(),
        );

        return $this->handleLogModel->insert_pickup_handle_log($logData);
    }

    /**
     * 插入订单操作日志
     * @author Jerry
     * @param int $order_id
     * @param string $content
     * @return bool|mixed
     */
    protected function insert_order_action($order_id = 0, $content = '')
    {
        $data = array(
            'order_id'          =>  $order_id,
            'action_user'       =>  '自动脚本',
            'order_status'      =>  OS_CONFIRMED,
            'shipping_status'   =>  SS_SHIPPED,
            'pay_status'        =>  PS_PAYED,
            'action_note'       =>  $content,
            'log_time'          =>  gmtime(),
            'action_type'       =>  4,
        );

        $orderActionModel = new OrderActionModel();
        return $orderActionModel->insert_order_action($data);
    }


    /**
     * 发送延时配送短信
     * Created by Jerry
     * @param $mobile
     * @param $userName
     * @param $orderSn
     * @param $userId
     * @param $remark
     * @return mixed
     */
    protected function send_pickup_order_sms($mobile, $userName, $orderSn, $userId, $remark, $type = 0,$chat_param=array())
    {
    	if ($type == 1) {
			$smsTypeName = 'order_pickup_warning_new';
		}else{
			$smsTypeName = 'order_remind_new';
		}

        return A("Smsapi")->send_message_api($smsTypeName,$mobile, $userName, 0, $orderSn, 0, $userId, $remark, $remark['best_time'],$chat_param);
    }
}